package com.tduck.cloud.datav.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.tduck.cloud.common.util.Result;
import com.tduck.cloud.datav.request.ChartDataRequest;
import com.tduck.cloud.datav.service.impl.ChartDataService;
import com.tduck.cloud.report.data.template.DataSearchTemplate;
import com.tduck.cloud.storage.cloud.OssStorageFactory;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 数据大屏通用
 *
 * @author : tduck
 * @since : 2021/06/08 15:32
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/datav")
public class DatavController {

    private final ChartDataService chartDataService;
    private final DataSearchTemplate dataSearchTemplate;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return
     * @throws IOException
     */
    @PostMapping("/upload")
    public Result avatar(@RequestParam("file") MultipartFile file) throws IOException {
        if (!file.isEmpty()) {
            String path = IdUtil.simpleUUID() + CharUtil.DOT + StrUtil.blankToDefault(FileUtil.extName(file.getOriginalFilename()), "png");
            String url = OssStorageFactory.getStorageService().upload(file.getInputStream(), path);
            return Result.success(url);
        }
        return Result.failed("上传文件异常，请联系管理员");
    }


    /**
     * 图表获取数据
     */
    @PostMapping("/chart/data")
    public Result getChartData(@RequestBody ChartDataRequest request) {
        if (StrUtil.isBlank(request.getIndexName()) ||
                CollUtil.isEmpty(request.getIndex())) {
            return Result.success();
        }
        return Result.success(chartDataService.getChartData(request));
    }

    /**
     * sql等获取数据
     */
    @PostMapping("/dataset/data")
    public Result getChartDatasetData(@RequestBody ChartDataRequest request) {
        if (StrUtil.isBlank(request.getIndexName()) ||
                CollUtil.isEmpty(request.getIndex())) {
            return Result.success();
        }
        return Result.success(chartDataService.getChartData(request));
    }

    /**
     * 获取字段去重列表
     */
    @GetMapping("/chart/field/distinct")
    public Result getFieldDistinct(@RequestParam("indexName") String indexName, @RequestParam("fieldId") String fieldId) {
        return Result.success(dataSearchTemplate.getFieldDistinctList(indexName, fieldId));
    }

}
